const R = require('ramda')
const bcrypt = require('bcrypt')
const UserStatus = require('./UserStatus')
const Entity = require('../../shared/entity/Entity')
const { getAddAndRemoveIdList } = require('../../shared/repository/helper')
const saltRounds = 10

const descriptor = {
  username: [
    { required: true, message: '用户名不能为空' },
    { type: 'string', min: 5, max: 30, message: '用户名长度为5-30' },
  ],
  password: [
    { required: true, message: '密码不能为空' },
    { type: 'string', min: 8, max: 100, message: '密码长度8-100' },
  ],
  email: { type: 'email', message: '邮箱格式不正确' },
  phone: { pattern: /1[3456789]\d{9}/, message: '手机号码格式不正确' },
}

class User extends Entity {
  username
  password
  email
  phone
  salt
  isSuperAdmin = false
  status = UserStatus.ENABLE
  lastLoginAt
  lastLoginIp
  roleList = []
  constructor(data) {
    super(descriptor, data)
    this.init(data)
  }
  async comparePassword(rawPassword) {
    return await bcrypt.compare(rawPassword, this.password)
  }
  isDisabled() {
    return this.status === UserStatus.DISABLE
  }
  async bcryptPassword() {
    if (!this.salt) {
      this.salt = await bcrypt.genSalt(saltRounds)
    }
    this.password = await bcrypt.hash(this.password, this.salt)
  }
  static create(data) {
    const user = new User(data)
    return user
  }
}

module.exports = User
